package com.youle.youleservice.manager;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.youle.youleservice.constance.Config;
import com.youle.youleservice.http.HttpRequest;
import com.youle.youleservice.listener.HttpCallback;

import java.io.IOException;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * Created by Administrator on 2018/8/8.
 */

public class OkhttpManager {



   private static OkhttpManager instance = new OkhttpManager();

  public static OkhttpManager getInstance(){
      return instance;
  }


  public static void post(String param, HttpCallback callback){
      post(Config.HTTP_URL,param,callback);
  }

    public static void post(String url,String param,final HttpCallback callback){
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        final HttpRequest request = new HttpRequest();
        RequestBody body=RequestBody.create(mediaType,param);
        final Message msg = new Message();
        request.post(url, body, new Callback() {
            @Override
            public void onFailure(Call call,final IOException e) {
               new Handler(Looper.getMainLooper()){
                   @Override
                   public void handleMessage(Message msg) {
                       super.handleMessage(msg);
                       callback.failure(-1,e.getMessage());
                   }
               }.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String content = response.body().string();
                new Handler(Looper.getMainLooper()){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        callback.succese(content);
                    }
                }.sendEmptyMessage(1);
            }
        });
    }



}
